<template>
    <div class="dashboard-container">
        <!-- 顶部日期选择器 -->
        <div class="date-picker-container">
            <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="~"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                class="date-picker"
            />
        </div>

        <!-- 统计卡片区域 -->
        <el-row :gutter="20" class="stats-row">
            <el-col :span="6">
                <el-card shadow="hover" class="stats-card">
                    <div class="stats-card-header">
                        <div class="stats-label">总销售额</div>
                        <el-icon class="info-icon"><InfoFilled /></el-icon>
                    </div>
                    <div class="stats-main-value">
                        <countup class="stats-number" :end="126560" />
                    </div>
                    <div class="stats-chart-container">
                        <div class="mini-chart" ref="miniChart0"></div>
                    </div>
                    <div class="stats-daily">日均销售额 ¥12,423</div>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card shadow="hover" class="stats-card">
                    <div class="stats-card-header">
                        <div class="stats-label">(服务) 总销售额</div>
                        <el-icon class="info-icon"><InfoFilled /></el-icon>
                    </div>
                    <div class="stats-main-value">
                        <countup class="stats-number" :end="8846" />
                    </div>
                    <div class="stats-chart-container">
                        <div class="mini-chart" ref="miniChart1"></div>
                    </div>
                    <div class="stats-daily">日均销售额 ¥12,423</div>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card shadow="hover" class="stats-card">
                    <div class="stats-card-header">
                        <div class="stats-label">(咨询) 总销售额</div>
                        <el-icon class="info-icon"><InfoFilled /></el-icon>
                    </div>
                    <div class="stats-main-value">
                        <countup class="stats-number" :end="6560" />
                    </div>
                    <div class="stats-chart-container">
                        <div class="mini-chart" ref="miniChart2"></div>
                    </div>
                    <div class="stats-daily">日均销售额 ¥12,423</div>
                </el-card>
            </el-col>
            <el-col :span="6">
                <el-card shadow="hover" class="stats-card">
                    <div class="stats-card-header">
                        <div class="stats-label">(商品) 总销售额</div>
                        <el-icon class="info-icon"><InfoFilled /></el-icon>
                    </div>
                    <div class="stats-main-value">
                        <countup class="stats-number" :end="6560" />
                    </div>
                    <div class="stats-chart-container">
                        <div class="mini-chart" ref="miniChart3"></div>
                    </div>
                    <div class="stats-daily">日均销售额 ¥12,423</div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 中间区域：销售额趋势和服务商排名 -->
        <el-row :gutter="20" class="middle-row">
            <el-col :span="16">
                <el-card shadow="hover" class="trend-card">
                    <div class="trend-header">
                        <div class="trend-tabs">
                            <el-tabs v-model="activeTab" class="trend-tabs-container">
                                <el-tab-pane label="销售额" name="sales"></el-tab-pane>
                            </el-tabs>
                            <div class="time-tabs">
                                <el-tag 
                                    v-for="time in timeTabs" 
                                    :key="time.value"
                                    :type="activeTimeTab === time.value ? 'primary' : ''"
                                    @click="activeTimeTab = time.value"
                                    class="time-tag"
                                >
                                    {{ time.label }}
                                </el-tag>
                            </div>
                        </div>
                    </div>
                    <div class="trend-chart" ref="trendChartRef"></div>
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card shadow="hover" class="ranking-card">
                    <div class="ranking-header">
                        <div class="ranking-title">服务商销售额排名</div>
                    </div>
                    <div class="ranking-list">
                        <div 
                            v-for="(item, index) in serviceRanking" 
                            :key="index" 
                            class="ranking-item"
                        >
                            <div 
                                class="ranking-number" 
                                :class="{ 'top-three': index < 3 }"
                            >
                                {{ index + 1 }}
                            </div>
                            <div class="ranking-name">{{ item.name }}</div>
                            <div class="ranking-value">{{ item.value.toLocaleString() }}</div>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 底部区域：热门搜索和类别占比 -->
        <el-row :gutter="20" class="bottom-row">
            <el-col :span="12">
                <el-card shadow="hover" class="search-card">
                    <div class="search-header">
                        <div class="search-title">线上热门搜索</div>
                    </div>
                    <div class="search-content">
                        <el-table :data="hotSearches" class="search-table">
                            <el-table-column prop="rank" label="排名" width="80" align="center" />
                            <el-table-column prop="product" label="商品服务" />
                            <el-table-column prop="users" label="用户数" width="100" align="center" />
                            <el-table-column prop="change" label="周涨幅" width="100" align="center">
                                <template #default="{ row }">
                                    <span :class="row.changeType === 'up' ? 'change-up' : 'change-down'">
                                        {{ row.change }}%
                                        <el-icon v-if="row.changeType === 'up'"><ArrowUp /></el-icon>
                                        <el-icon v-else><ArrowDown /></el-icon>
                                    </span>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="pagination-container">
                            <el-pagination
                                v-model:current-page="currentPage"
                                :page-size="pageSize"
                                :total="total"
                                layout="prev, pager, next"
                                class="pagination"
                            />
                            <el-select v-model="pageSize" class="page-size-select">
                                <el-option label="5条/页" :value="5" />
                                <el-option label="10条/页" :value="10" />
                                <el-option label="20条/页" :value="20" />
                            </el-select>
                            <div class="jump-to">
                                跳至 <el-input v-model="jumpPage" class="jump-input" /> 页
                                </div>
                            </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card shadow="hover" class="category-card">
                    <div class="category-header">
                        <div class="category-title">销售额类别占比</div>
                    </div>
                    <div class="category-content">
                        <div class="category-chart">
                            <div class="donut-chart" ref="categoryChartRef"></div>
                                </div>
                        <div class="category-legend">
                            <div 
                                v-for="(item, index) in categoryData" 
                                :key="index" 
                                class="legend-item"
                            >
                                <div class="legend-dot" :style="{ backgroundColor: item.color }"></div>
                                <div class="legend-text">{{ item.name }}</div>
                                <div class="legend-percent">{{ item.percent }}%</div>
                                <div class="legend-value">¥{{ item.value.toLocaleString() }}</div>
                            </div>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script setup lang="ts" name="dashboard">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue';
import countup from '@/components/countup.vue';
import * as echarts from 'echarts';
import chinaMap from '@/utils/china';

// ECharts实例管理
let trendChart: echarts.ECharts | null = null;
let categoryChart: echarts.ECharts | null = null;
let miniCharts: echarts.ECharts[] = [];

// Vue refs
const miniChart0 = ref<HTMLElement>();
const miniChart1 = ref<HTMLElement>();
const miniChart2 = ref<HTMLElement>();
const miniChart3 = ref<HTMLElement>();
const trendChartRef = ref<HTMLElement>();
const categoryChartRef = ref<HTMLElement>();

// 注册中国地图
echarts.registerMap('china', chinaMap);

// 日期选择器 - 默认当天
const today = new Date();
const todayStr = today.toISOString().split('T')[0];
const dateRange = ref([todayStr, todayStr]);

// 标签页状态
const activeTab = ref('sales');
const activeTimeTab = ref('year');

// 时间标签页选项
const timeTabs = ref([
    { label: '今日', value: 'today' },
    { label: '本周', value: 'week' },
    { label: '本月', value: 'month' },
    { label: '全年', value: 'year' }
]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(25);
const jumpPage = ref(5);

// 迷你图表配置
const miniChartOption = computed(() => ({
    grid: { left: 0, right: 0, top: 0, bottom: 0 },
    xAxis: { type: 'category', show: false },
    yAxis: { type: 'value', show: false },
    series: [{
        type: 'line',
        data: [20, 30, 25, 35, 28, 40, 32],
        smooth: true,
        lineStyle: { color: '#8B5CF6', width: 2 },
        areaStyle: { color: 'rgba(139, 92, 246, 0.1)' },
        symbol: 'none'
    }]
}));

// 销售额趋势图表配置
const salesTrendOption = computed(() => ({
    title: {
        text: '销售额趋势',
        left: 'left',
        top: '5%',
        textStyle: {
            fontSize: 18,
            fontWeight: 'bold',
            color: '#333'
        }
    },
    grid: { 
        left: '5%', 
        right: '5%', 
        top: '20%', 
        bottom: '5%', 
        containLabel: true 
    },
    xAxis: {
        type: 'category',
        data: ['10月', '11月', '12月', '01月', '02月', '03月', '04月', '05月', '06月', '07月', '08月', '09月'],
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { 
            color: '#666',
            fontSize: 12,
            interval: 0
        }
    },
    yAxis: {
        type: 'value',
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: { 
            color: '#666',
            fontSize: 12
        },
        splitLine: { 
            lineStyle: { color: '#f0f0f0' }
        },
        min: 0,
        max: 600
    },
    series: [{
        type: 'bar',
        data: [200, 300, 400, 250, 350, 500, 300, 400, 600, 350, 450, 300],
        itemStyle: { color: '#3B82F6' },
        barWidth: '50%',
        barMaxWidth: 30
    }]
}));

// 服务商排名数据
const serviceRanking = ref([
    { name: '服务商1号', value: 323234 },
    { name: '服务商2号', value: 323234 },
    { name: '服务商3号', value: 323234 },
    { name: '服务商1号', value: 323234 },
    { name: '服务商1号', value: 323234 },
    { name: '服务商1号', value: 323234 },
    { name: '服务商7号', value: 323234 }
]);

// 热门搜索数据
const hotSearches = ref([
    { rank: 1, product: '八字', users: 2234, change: 128, changeType: 'up' },
    { rank: 2, product: '看命', users: 2234, change: 3, changeType: 'up' },
    { rank: 3, product: '看命', users: 2234, change: 58, changeType: 'up' },
    { rank: 4, product: '看命', users: 2234, change: 58, changeType: 'down' },
    { rank: 5, product: '短裤', users: 2234, change: 58, changeType: 'down' }
]);

// 类别数据
const categoryData = ref([
    { name: '商品1', percent: 36, value: 4544, color: '#3B82F6' },
    { name: '服务', percent: 20, value: 4544, color: '#10B981' },
    { name: '咨询', percent: 16, value: 4544, color: '#F59E0B' },
    { name: '商品2', percent: 12, value: 3000, color: '#EF4444' },
    { name: '商品3', percent: 10, value: 2500, color: '#8B5CF6' },
    { name: '其他', percent: 6, value: 1500, color: '#6B7280' }
]);

// 类别占比饼图配置
const categoryOption = computed(() => ({
    series: [{
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '50%'],
        data: categoryData.value.map(item => ({
            value: item.value,
            name: item.name,
            itemStyle: { color: item.color }
        })),
        label: { show: false },
        labelLine: { show: false },
        emphasis: {
            itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
        }
    }],
    graphic: {
        type: 'text',
        left: 'center',
        top: 'center',
        style: {
            text: '销售额\n¥123,224',
            textAlign: 'center',
            fill: '#333',
            fontSize: 14,
            fontWeight: 'bold'
        }
    }
}));

// 初始化图表
const initCharts = () => {
    nextTick(() => {
        // 延迟初始化，确保DOM完全渲染
        setTimeout(() => {
            // 初始化迷你图表
            const miniChartRefs = [miniChart0, miniChart1, miniChart2, miniChart3];
            miniChartRefs.forEach((chartRef, index) => {
                if (chartRef.value) {
                    console.log(`初始化迷你图表 ${index}:`, chartRef.value);
                    const chart = echarts.init(chartRef.value);
                    chart.setOption(miniChartOption.value);
                    miniCharts.push(chart);
                } else {
                    console.log(`未找到迷你图表容器 ${index}`);
                }
            });
            
            // 初始化趋势图表
            if (trendChartRef.value) {
                console.log('初始化趋势图表:', trendChartRef.value);
                trendChart = echarts.init(trendChartRef.value);
                trendChart.setOption(salesTrendOption.value);
            } else {
                console.log('未找到趋势图表容器');
            }
            
            // 初始化类别图表
            if (categoryChartRef.value) {
                console.log('初始化类别图表:', categoryChartRef.value);
                categoryChart = echarts.init(categoryChartRef.value);
                categoryChart.setOption(categoryOption.value);
            } else {
                console.log('未找到类别图表容器');
            }
        }, 500);
    });
};

// 窗口大小变化处理
let resizeObserver: ResizeObserver | null = null;

const handleResize = () => {
    // 延迟执行，确保DOM更新完成
    setTimeout(() => {
        // 重新调整所有图表大小
        miniCharts.forEach(chart => {
            if (chart && typeof chart.resize === 'function') {
                chart.resize();
            }
        });
        if (trendChart && typeof trendChart.resize === 'function') {
            trendChart.resize();
        }
        if (categoryChart && typeof categoryChart.resize === 'function') {
            categoryChart.resize();
        }
    }, 100);
};

onMounted(() => {
    // 初始化图表
    initCharts();
    
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize);
    
    // 使用ResizeObserver监听容器大小变化
    if (window.ResizeObserver) {
        resizeObserver = new ResizeObserver(() => {
            handleResize();
        });
        
        // 监听所有图表容器
        setTimeout(() => {
            const chartContainers = document.querySelectorAll('.trend-chart, .donut-chart, .mini-chart');
            chartContainers.forEach(container => {
                if (resizeObserver) {
                    resizeObserver.observe(container);
                }
            });
        }, 300);
    }
});

onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    if (resizeObserver) {
        resizeObserver.disconnect();
        resizeObserver = null;
    }
    
    // 销毁图表实例
    miniCharts.forEach(chart => {
        if (chart && typeof chart.dispose === 'function') {
            chart.dispose();
        }
    });
    if (trendChart && typeof trendChart.dispose === 'function') {
        trendChart.dispose();
    }
    if (categoryChart && typeof categoryChart.dispose === 'function') {
        categoryChart.dispose();
    }
    
    // 清空数组和变量
    miniCharts = [];
    trendChart = null;
    categoryChart = null;
});
</script>

<style scoped>
.card-body {
    display: flex;
    align-items: center;
    height: 100px;
    padding: 0;
}

/* 使用深度选择器修改Element Plus组件样式 */
:deep(.el-card__body) {
    padding: 0 !important;
}

:deep(.el-tabs__header) {
    margin: 0 !important;
}

:deep(.el-tabs__nav-wrap) {
    padding: 0 !important;
}

:deep(.el-tabs__content) {
    padding: 0 !important;
}
</style>
<style scoped>
.card-content {
    flex: 1;
    text-align: center;
    font-size: 14px;
    color: #999;
}

.card-num {
    font-size: 30px;
}

.card-icon {
    font-size: 50px;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
    color: #fff;
}

.bg1 {
    background: #2d8cf0;
}

.bg2 {
    background: #64d572;
}

.bg3 {
    background: #f25e43;
}

.bg4 {
    background: #e9a745;
}

.color1 {
    color: #2d8cf0;
}

.color2 {
    color: #64d572;
}

.color3 {
    color: #f25e43;
}

.color4 {
    color: #e9a745;
}

.chart {
    width: 100% !important;
    height: 400px;
}

.card-header {
    padding-left: 10px;
    margin-bottom: 20px;
}

.card-header-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 5px;
}

.card-header-desc {
    font-size: 14px;
    color: #999;
}

.timeline-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 16px;
    color: #000;
}

.timeline-time,
.timeline-desc {
    font-size: 12px;
    color: #787878;
}

.rank-item {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.rank-item-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #f2f2f2;
    text-align: center;
    line-height: 40px;
    margin-right: 10px;
}

.rank-item-content {
    flex: 1;
}

.rank-item-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #343434;
    margin-bottom: 10px;
}

.rank-item-desc {
    font-size: 14px;
    color: #999;
}
.map-chart {
    width: 100%;
    height: 350px;
}

/* 新增的样式 */
.dashboard-container {
    padding: 10px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.date-picker-container {
    margin-bottom: 10px;
}

.date-picker {
    width: 300px;
}

.stats-row {
    margin-bottom: 10px;
}

.stats-card {
    border-radius: 8px;
    overflow: hidden;
    padding: 12px;
    height: 140px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.stats-card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 6px;
}

.stats-label {
    font-size: 13px;
    color: #999;
    font-weight: normal;
}

.info-icon {
    color: #999;
    font-size: 14px;
    width: 18px;
    height: 18px;
    border-radius: 50%;
    background-color: #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: center;
}

.stats-main-value {
    text-align: center;
    margin: 6px 0;
}

.stats-number {
    font-size: 28px;
    font-weight: bold;
    color: #333;
    display: block;
}

.stats-chart-container {
    height: 30px;
    margin: 6px 0;
}

.mini-chart {
    width: 100% !important;
    height: 100%;
}

.stats-daily {
    font-size: 11px;
    color: #999;
    text-align: center;
    margin-top: 4px;
}

.middle-row {
    margin-bottom: 10px;
}

.trend-card {
    border-radius: 8px;
    height: 400px;
    display: flex;
    flex-direction: column;
}

.trend-header {
    padding: 10px;
    flex-shrink: 0;
}

.trend-tabs {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.trend-tabs-container {
    flex: 1;
}

.time-tabs {
    display: flex;
    gap: 8px;
}

.time-tag {
    cursor: pointer;
    font-size: 14px;
}

.trend-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
}

.trend-chart {
    width: 100% !important;
    flex: 1;
    padding: 10px;
    padding-top: 0;
    height: 320px;
}

.ranking-card {
    border-radius: 8px;
    height: 400px;
    display: flex;
    flex-direction: column;
}

.ranking-header {
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
    flex-shrink: 0;
}

.ranking-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
}

.ranking-list {
    padding: 15px;
    flex: 1;
    overflow-y: auto;
    max-height: 300px;
}

.ranking-item {
    display: flex;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #f5f5f5;
    min-height: 40px;
}

.ranking-item:last-child {
    border-bottom: none;
}

.ranking-number {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    background-color: #f0f0f0;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    color: #666;
    margin-right: 12px;
    flex-shrink: 0;
}

.ranking-number.top-three {
    background-color: #1e40af;
    color: white;
}

.ranking-name {
    flex: 1;
    font-size: 13px;
    color: #333;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-right: 8px;
}

.ranking-value {
    font-size: 13px;
    color: #666;
    flex-shrink: 0;
}

.bottom-row {
    margin-bottom: 10px;
}

.search-card {
    border-radius: 8px;
    height: 400px;
    display: flex;
    flex-direction: column;
}

.search-header {
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
    flex-shrink: 0;
}

.search-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
}

.search-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.search-table {
    flex: 1;
    margin: 15px;
}

.pagination-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px;
    border-top: 1px solid #f0f0f0;
    flex-shrink: 0;
}

.pagination {
    flex: 1;
}

.page-size-select {
    width: 100px;
    margin: 0 15px;
}

.jump-to {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #666;
}

.jump-input {
    width: 50px;
    margin: 0 8px;
}

.change-up {
    color: #67c23a;
    display: flex;
    align-items: center;
    gap: 3px;
}

.change-down {
    color: #f56c6c;
    display: flex;
    align-items: center;
    gap: 3px;
}

.category-card {
    border-radius: 8px;
    height: 400px;
    display: flex;
    flex-direction: column;
}

.category-header {
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
    flex-shrink: 0;
}

.category-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
}

.category-content {
    display: flex;
    padding: 15px;
    flex: 1;
    overflow: hidden;
}

.category-chart {
    flex: 1;
    position: relative;
}

.donut-chart {
    width: 100% !important;
    height: 100%;
}

.category-legend {
    flex: 1;
    padding-left: 15px;
    overflow-y: auto;
}

.legend-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.legend-dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    margin-right: 8px;
}

.legend-text {
    flex: 1;
    font-size: 14px;
    color: #333;
}

.legend-percent {
    font-size: 14px;
    color: #666;
    margin-right: 8px;
}

.legend-value {
    font-size: 14px;
    color: #666;
}
</style>
